﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArgusPCLib.Collections.Generic;

namespace ArgusPCLib
{
	/// <summary>
	/// Defines Extension-Methods for classes in the <see cref="System.Collections.Generic"/> namespace.
	/// </summary>
	public static class SystemCollectionsGenericExtensions
	{
		public static bool Contains<T>(this T[] array, T item)
		{
			foreach (T t in array)
			{
				if (t.Equals(item))
					return true;
			}
			return false;
		}

		public static T Last<T>(this IList<T> list)
		{
			return list[list.Count - 1];
		}

		public static void RemoveLast<T>(this IList<T> list)
		{
			list.RemoveAt(list.Count - 1);
		}

		public static Dictionary<TKey,List<TValue>> Group<TKey,TValue>(this IEnumerable<TValue> enumerable, Func<TValue, TKey> getKey)
		{
			Dictionary<TKey, List<TValue>> dict = new Dictionary<TKey, List<TValue>>();
			foreach (TValue value in enumerable)
			{
				List<TValue> list;
				TKey key = getKey(value);
				if (dict.TryGetValue(key, out list) == false)
				{
					list = new List<TValue>();
					dict.Add(key, list);
				}
				list.Add(value);
			}
			return dict;
		}

		public static ItemPair<TKey,TValue[]>[] ToArray<TKey,TValue>(this Dictionary<TKey, IList<TValue>> dictionary)
		{
			ItemPair<TKey, TValue[]>[] RetVal = new ItemPair<TKey, TValue[]>[dictionary.Count];
			int i = 0;
			foreach (KeyValuePair<TKey, IList<TValue>> item in dictionary)
			{
				RetVal[i] = new ItemPair<TKey, TValue[]>(item.Key, item.Value.ToArray());
				i++;
			}
			return RetVal;
		}
	}
}